import { Injectable } from '@nestjs/common';
import { CreateRoleDto } from './dto/create-role.dto';
import { UpdateRoleDto } from './dto/update-role.dto';
import { ResultData } from '@/common/utils/result';
import { instanceToPlain } from 'class-transformer';
import { InjectRepository } from '@nestjs/typeorm';
import { Like, Repository } from 'typeorm';
import { Role } from '@/modules/system/role/entities/role.entity';
import { User } from '@/modules/system/user/entities/user.entity';
import { UserRole } from '@/modules/system/user-role/entities/user-role.entity';

@Injectable()
export class RoleService {
    constructor(
        @InjectRepository(Role)
        private readonly roleRepository: Repository<Role>,
        @InjectRepository(User)
        private readonly userRepository: Repository<User>,
        @InjectRepository(UserRole)
        private readonly userRoleRepository: Repository<UserRole>,
    ) {
    }
    
    async create(createRoleDto: CreateRoleDto) {
        return ResultData.ok(instanceToPlain(await this.roleRepository.save(createRoleDto)));
    }
    
    async findAll(dto) {
        const { page, size, name, id } = dto;
        const take = size || 15;
        const skip = ((page || 1) - 1) * take;
        const where = {
            ...(id === 0 || id ? { id } : null),
            ...(name ? { name: Like(`%${name}%`) } : null),
        };
        return ResultData.rowOk(instanceToPlain(await this.roleRepository.findAndCount({
            order: {
                sort: 'DESC',
                id: 'DESC',
            },
            where,
            skip,
            take,
        })));
    }
    
    async findAllNoPage() {
        return ResultData.ok(instanceToPlain(await this.roleRepository.find({
            order: {
                sort: 'DESC',
                id: 'DESC',
            },
        })));
    }
    
    findOne(id: number) {
        return `This action returns a #${id} role`;
    }
    
    async update(id: number, updateRoleDto: UpdateRoleDto) {
        return ResultData.ok(await this.roleRepository.update(id, updateRoleDto), '更新成功');
    }
    
    async remove(id: number) {
        return ResultData.ok(await this.roleRepository.delete(id), '删除成功');
    }
    
    
}
